package com.lyeducation.controllers.video;

import com.lyeducation.controllers.base.BaseController;
import com.lyeducation.controllers.dto.PayRequestDTO;
import com.lyeducation.controllers.dto.UpdVideoDto;
import com.lyeducation.controllers.dto.UserVideoCommentDto;
import com.lyeducation.controllers.dto.VideoDto;
import com.lyeducation.core.base.SysConstants;
import com.lyeducation.core.base.TokenConstants;
import com.lyeducation.core.video.VideoQueryEnum;
import com.lyeducation.core.video.VideoService;
import com.lyeducation.entities.course.VideoEntity;
import com.lyeducation.entities.course.middle.ChapterVideoEntity;
import com.lyeducation.entities.course.middle.UserVideoCommentClickPraiseEntity;
import com.lyeducation.entities.course.middle.UserVideoCommentEntity;
import com.lyeducation.repository.VideoRepository;
import com.lyeducation.security.config.SecurityPrincipalContext;
import com.lyeducation.util.HttpUtil;
import com.lyeducation.util.JsonUtils;
import com.lyeducation.util.Md5Utils;
import com.lyeducation.util.StringUtils;
import com.lyeducation.util.controllerUtil.JsonConstans;
import com.lyeducation.util.controllerUtil.JsonResult;
import freemarker.core.ParseException;
import freemarker.template.*;
import io.swagger.annotations.*;
import net.sf.json.JSONObject;
import org.hibernate.transform.Transformers;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

@Api(
        tags = {"视频video-api"},
        description = "视频模块接口{mId}需要传入菜单id"
)
@RestController
@RequestMapping("video/{mid}")
@Transactional(rollbackFor = Exception.class, readOnly = false, propagation = Propagation.REQUIRED)
public class VideoController extends BaseController<VideoEntity> {
    @Autowired
    private VideoRepository videoRepository;
    @Autowired
    private VideoService videoService;

    @PutMapping("/test")
    private Map test(@RequestBody Map<String, String> map) {
        return map;
    }

    @ApiOperation(value = "视频热推首页", notes = "")
    @Override
    public JsonResult onLoad() {
        return JsonResult.putSuccess(videoService.findData(VideoQueryEnum.NEW));
    }

    @ApiOperation(value = "根据视频类型查询单个视频", notes = "{\"type\" : \"热门\",pageSize : 5,pageNo : 1}")
    @PostMapping("selVideosByType")
    public JsonResult selVideosByType(@RequestBody @ApiParam(value = "查询参数") QueryPage queryPage) {
        Map map = new HashMap();
        map.put("type", queryPage.getType());
        return JsonResult.putSuccess(
                videoRepository.findPageByNativeQueryFileds(
                        "select * from video where type=:type and videoAccessRole=0",
                        map,
                        queryPage.getPageNo(),
                        queryPage.getPageSize()));
    }

    @ApiOperation(value = "显示视频评论", notes = "显示视频评论")
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "videoId",
                    value = "视频id",
                    required = true,
                    dataType = "String",
                    paramType = "path"
            ),
            @ApiImplicitParam(
                    name = "pageNo",
                    value = "页码",
                    required = false,
                    dataType = "int",
                    paramType = "path"
            ),
            @ApiImplicitParam(name = "pageSize", value = "页数", required = false, paramType = "path")
    })
    @GetMapping("selVideoCommentByVideoId/{videoId}/{pageNo}/{pageSize}")
    public JsonResult selVideoComment(
            @PathVariable String videoId, @PathVariable int pageSize, @PathVariable int pageNo) {
        Map<String, Object> map = new HashMap();
        map.put("videoId", videoId);

        map =
                videoRepository.findPageByNativeQueryFileds(
                        "SELECT uvc.id,uvc.toId,uvc.replySize,uvc.videoId,uvc.score, uvc.`comment`,su.`name` as name ,uvc.parentId,uvc.sort FROM user_video_comment as uvc LEFT JOIN sys_user as su on uvc.id=su.id where uvc.videoId=:videoId",
                        map,
                        Transformers.aliasToBean(UserVideoCommentDto.class),
                        pageNo,
                        pageSize);
        List<UserVideoCommentDto> userVideoCommentDtos =
                (List<UserVideoCommentDto>) map.get(SysConstants.ROWS.getValue());

        //        UpDownTreeEntityService<UserVideoCommentDto> upDownTreeEntityService =
        //
        // UpDownTreeEntityServiceImpl.createUpDownTreeEntityService(UserVideoCommentDto.class);
        //        upDownTreeEntityService.upDownTreeEntity(userVideoCommentDtos);
        if (userVideoCommentDtos.size() > 1)
            return JsonResult.putSuccess(UserVideoCommentDto.upDownTreeEntity(userVideoCommentDtos));
        return JsonResult.putSuccess(userVideoCommentDtos);
    }

    @ApiOperation(
            value = "添加更新视频评论",
            notes =
                    "{\"id\":\"155143842005142957\",\n"
                            + "\t\"sort\":0,\n"
                            + "    \"comment\": \"对用户首个视频评论下的视频评论进行评论评论3\",\n"
                            + "    \"toUserId\": \"155143838309328080\",\n"
                            + "    \"videoId\":\"1\",\"parentId\":\"155143838309328080\" }"
    )
    @PostMapping("addUpdVideoComment")
    public JsonResult addUpdVideoComment(@RequestBody UserVideoCommentDto userVideoCommentDto) {
        UserVideoCommentEntity userVideoCommentEntity = null;
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        if (StringUtils.trimToNull(userVideoCommentDto.getVideoId()) != null) {
            if (StringUtils.trimToNull(userVideoCommentDto.getId()) != null) {
                userVideoCommentEntity =
                        videoRepository.findById(UserVideoCommentEntity.class, userVideoCommentDto.getId());
                //                BeanUtils.copyProperties(userVideoCommentDto, userVideoCommentEntity);
                if (userVideoCommentEntity != null) {
                    userVideoCommentEntity.setComment(userVideoCommentDto.getComment());
                    userVideoCommentEntity.setUpdateTime(timestamp);
                    videoRepository.update(userVideoCommentEntity);
                } else {
                    return JsonResult.putFail("未查询到该视频评论");
                }
            } else {
                userVideoCommentEntity = new UserVideoCommentEntity();
                BeanUtils.copyProperties(userVideoCommentDto, userVideoCommentEntity);
                userVideoCommentEntity.setId(TokenConstants.generateUserId());
                userVideoCommentEntity.setCreateTime(timestamp);
                userVideoCommentEntity.setUserId(SecurityPrincipalContext.getUserDetailsImpl().getId());
                userVideoCommentEntity.setUpdateTime(timestamp);
                userVideoCommentEntity.setName(SecurityPrincipalContext.getUserDetailsImpl().getName());
                videoRepository.save(userVideoCommentEntity);
                if (StringUtils.trimToNull(userVideoCommentEntity.getToId()) != null) {
                    UserVideoCommentEntity toUserVideoCommentEntity =
                            videoRepository.findById(
                                    UserVideoCommentEntity.class, userVideoCommentEntity.getToId());
                    if (toUserVideoCommentEntity != null) {
                        toUserVideoCommentEntity.setReplySize(toUserVideoCommentEntity.getReplySize() + 1);
                    }
                }
            }
            return JsonResult.putSuccess();
        }
        return JsonResult.putFail("视频id不能为空");
    }

    @ApiOperation(value = "删除视频评论", notes = "删除视频评论")
    @GetMapping("delVideoComment/{id}")
    @ApiImplicitParam(
            name = "id",
            value = "视频评论id",
            required = true,
            dataType = "String",
            paramType = "path"
    )
    public JsonResult delVideoComment(@ApiParam @PathVariable String id) {
        if (StringUtils.isNotBlank(id)) {
//            删除评论及其关联的评论
//            删除该评论
            videoRepository.deleteById(UserVideoCommentEntity.class, id);
            Map map = new HashMap();
//            其他人对本评论的评论需要删除
            map.put("toId", id);
            videoRepository.deleteByMap(UserVideoCommentEntity.class, map);
            map.clear();
            map.put("parentId", id);
//其下级评论需要删除
            videoRepository.deleteByMap(UserVideoCommentEntity.class, map);
            map.clear();
            map.put("commentId", id);
            map.put("userId", SecurityPrincipalContext.getUserDetailsImpl().getId());
//            删除该评论对应的点赞
            videoRepository.deleteByMap(UserVideoCommentClickPraiseEntity.class, map);
            return JsonResult.putSuccess();
        }
        return JsonResult.putFail(JsonConstans.ERR_NOTVALID_AUTH);
    }

    @ApiOperation(value = "添加用户视频评论点赞", notes = "添加用户视频评论点赞")
    @GetMapping("addUserVideoCommentClickPraise/{commentId}")
    public JsonResult addUserVideoCommentClickPraise(@PathVariable String commentId) {
        UserVideoCommentClickPraiseEntity userVideoCommentClickPraiseEntity =
                new UserVideoCommentClickPraiseEntity();
        userVideoCommentClickPraiseEntity.setCommentId(commentId);
        userVideoCommentClickPraiseEntity.setUserId(
                SecurityPrincipalContext.getUserDetailsImpl().getId());
        videoRepository.save(userVideoCommentClickPraiseEntity);
        List<UserVideoCommentEntity> userVideoComments =
                videoRepository.findByFiled(UserVideoCommentEntity.class, "id", commentId);
        UserVideoCommentEntity userVideoCommentEntity = userVideoComments.get(0);
        userVideoCommentEntity.setScore((userVideoCommentEntity.getSort() + 1));
        videoRepository.update(userVideoCommentEntity);
        return JsonResult.putSuccess();
    }

    @ApiOperation(value = "删除用户视频评论点赞", notes = "删除用户视频评论点赞")
    @GetMapping("delUserVideoCommentClickPraise/{commentId}")
    public JsonResult delUserVideoCommentClickPraise(@PathVariable String commentId) {
        LinkedHashMap<String, Object> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("commentId", commentId);
        linkedHashMap.put("userId", SecurityPrincipalContext.getUserDetailsImpl().getId());
        if (videoRepository.deleteByMap(UserVideoCommentClickPraiseEntity.class, linkedHashMap)) {
            List<UserVideoCommentEntity> userVideoComments =
                    videoRepository.findByFiled(UserVideoCommentEntity.class, "id", commentId);
            UserVideoCommentEntity userVideoCommentEntity = userVideoComments.get(0);
            userVideoCommentEntity.setScore((userVideoCommentEntity.getSort() - 1));
            videoRepository.update(userVideoCommentEntity);
        }
        return JsonResult.putSuccess();
    }

    //    @GetMapping("addUserVideoClickPraise/{videoId}")
    //    public JsonResult addUserVideoClickPraise(@PathVariable String videoId) {
    //
    //        if (StringUtils.isNotBlank(videoId)) {
    //            UserVideoClickPraiseEntity userVideoClickPraiseEntity = new
    // UserVideoClickPraiseEntity();
    //
    // userVideoClickPraiseEntity.setUserId(SecurityPrincipalContext.getUserDetailsImpl().getId());
    //            userVideoClickPraiseEntity.setVideoId(videoId);
    //            videoRepository.save(userVideoClickPraiseEntity);
    //            return JsonResult.putSuccess();
    //        }
    //        return JsonResult.putFail(JsonConstans.ERR_NOTVALID_AUTH);
    //    }
    //
    //    @GetMapping("delUserVideoClickPrais/{videoId}")
    //    public JsonResult delUserVideoClickPraise(@PathVariable String videoId) {
    //        if (StringUtils.isNotBlank(videoId)) {
    //            Map<String, Object> map = new HashMap();
    //            map.put("userId", SecurityPrincipalContext.getUserDetailsImpl().getId());
    //            map.put("videoId", videoId);
    //            videoRepository.deleteByMap(UserVideoClickPraiseEntity.class, map);
    //            return JsonResult.putSuccess();
    //        }
    //        return JsonResult.putFail(JsonConstans.ERR_NOTVALID_AUTH);
    //    }

    @ApiOperation(value = "删除视频", notes = "删除视频")
    @GetMapping("/delVideo/{videoId}")
    public JsonResult delVideo(@PathVariable String videoId) {
        if (StringUtils.isNotBlank(videoId)) {
            Boolean result = videoRepository.softDeleteById(videoId);
            if (result) {
                return JsonResult.putSuccess();
            } else {
                return JsonResult.putFail(JsonConstans.ERR_NOT_EXISTED);
            }
        } else {
            return JsonResult.putFail(JsonConstans.ERR_NOTVALID_AUTH);
        }
    }

    @ApiOperation(value = "通过章节删除视频", notes = "删除视频")
    @GetMapping("/delVideoByChapter/{chapterId}")
    public JsonResult delVideoByChapter(@PathVariable String chapterId) {
        if (StringUtils.trimToNull(chapterId) != null) {
            LinkedHashMap map = new LinkedHashMap();
            map.put("chapterId", chapterId);
            List<ChapterVideoEntity> chapterVideoEntities =
                    videoRepository.findByFileds(ChapterVideoEntity.class, map);
            List<String> videoIds = new ArrayList<>();
            for (ChapterVideoEntity chapterVideoEntity : chapterVideoEntities) {
                videoIds.add(chapterVideoEntity.getVideoId());
            }
            map.clear();
            map.put("ids", videoIds);
            int result = videoRepository.updateFileds("set isDelete=true where id in(:ids)", map, null);
            if (result > 0) {
                return JsonResult.putSuccess();
            } else {
                return JsonResult.putFail(JsonConstans.ERR_NOT_EXISTED);
            }
        } else {
            return JsonResult.putFail(JsonConstans.ERR_NOTVALID_AUTH);
        }
    }

    @ApiOperation(value = "视频详情", notes = "视频详情")
    @GetMapping("/videoInfo/{videoId}")
    public JsonResult videoInfo(@PathVariable String videoId) {

        if (StringUtils.isNotBlank(videoId)) {
            Object obj = videoRepository.findById(videoId);
            if (obj == null) {
                return JsonResult.putFail(JsonConstans.ERR_NOT_EXISTED);
            } else {
                return JsonResult.putSuccess(obj);
            }
        } else {
            return JsonResult.putFail(JsonConstans.ERR_NOTVALID_AUTH);
        }
    }

    @ApiOperation(value = "修改视频", notes = "修改视频")
    @PostMapping("/updateVideo")
    public JsonResult updateVideo(@RequestBody UpdVideoDto updVideoDto) {
        return videoService.updVideoMsg(updVideoDto);
    }

    @ApiOperation(value = "新增视频", notes = "新增视频")
    @PostMapping("/newVideo")
    public JsonResult newVideo(@RequestBody VideoDto videoDto) {
        videoService.addVideo(videoDto);
        return JsonResult.putSuccess();
    }

    @ApiOperation(value = "通过章节查询视频", notes = "查询视频")
    @GetMapping("/selVideoByChapterId/{chapterId}/{pageNo}/{pageSize}")
    public JsonResult selVideoBychapterId(
            @PathVariable String chapterId, @PathVariable int pageSize, @PathVariable int pageNo) {
        return videoService.selVideoByChartId(chapterId, pageNo, pageSize);
    }

    @ApiOperation(value = "订单支付测试", notes = "订单支付测试")
    //    @PostMapping("/orderPay")
    @GetMapping("/orderPay")
    public JsonResult orderPay() {
        String url = "http://localhost:8080/pay/alipay/wappay";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("totalAmount", "0.01");
        //        jsonObject.put("notifyUrl", "http://localhost:8763/notifyUrl");
        //        jsonObject.put("returnUrl", "http://localhost:8763/returnUrl");
        jsonObject.put("timeoutExpress", "24h");
        jsonObject.put("outTradeNo", "20190106061620191107");
        jsonObject.put("subject", "泡泡熊毛绒玩具");
        jsonObject.put("appId", "2019010702192019117");
        jsonObject = JsonUtils.getSortJson(jsonObject);
        //        jsonObject.put("sign", "L2yvkR9aLmh0zwIr3UkNFw");
        jsonObject.put("sign", "PfC1hQ19Df38uQ2XFOY7sg==");
        String sort = jsonObject.toString();
        String resultStr = null;
        if (jsonObject.has("totalAmount")
                && jsonObject.has("timeoutExpress")
                && jsonObject.has("outTradeNo")
                && jsonObject.has("subject")
                && jsonObject.has("appId")
                && jsonObject.has("sign")) {
            if (jsonObject.get("totalAmount").equals("")
                    || jsonObject.get("timeoutExpress").equals("")
                    || jsonObject.get("outTradeNo").equals("")
                    || jsonObject.get("subject").equals("")
                    || jsonObject.get("appId").equals("")
                    || jsonObject.get("sign").equals("")) {
                return JsonResult.putFail(JsonConstans.ERR_WRONG_PARAM);
            } else {
                try {
                    resultStr = HttpUtil.doPut(url, sort);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return JsonResult.putSuccess(resultStr);
            }
        } else {
            return JsonResult.putFail(JsonConstans.ERR_WRONG_PARAM);
        }
    }

    public static void main(String[] args) {
        String url = "http://localhost:8080/pay/alipay/wappay";
        PayRequestDTO payRequestDTO = new PayRequestDTO();
        payRequestDTO.setAppId("2019010702192019117");
        payRequestDTO.setOutTradeNo("20190106061620191107");
        payRequestDTO.setSubject("泡泡熊毛绒玩具");
        //        payRequestDTO.setTotalAmount("0.01");
        payRequestDTO.setTimeoutExpress("24h");
        String json = Md5Utils.setSignWithJsonObj(payRequestDTO, "TEVBRElOR19FQUdMRQ==");
        System.out.println(json);
        String resultStr = null;
        try {
            resultStr = HttpUtil.doPut(url, json);

            System.out.println(resultStr);
        } catch (Exception e) {
            e.printStackTrace();
        }

        FileWriter out = null;
        try {
            // 通过FreeMarker的Confuguration读取相应的模板文件
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
            // 设置模板路径
            configuration.setDirectoryForTemplateLoading(new File("C:\\Users\\Sky1in3\\Desktop"));
            // 设置默认字体
            configuration.setDefaultEncoding("utf-8");

            // 获取模板
            Template template = configuration.getTemplate("static.html");
            // 设置模型
            //            User user = new User("tom", "hahahah", 28, "上海市");
            Map<String, String> map = new HashMap<>();
            map.put("paydata", resultStr);
            // 设置输出文件
            File file = new File("C:\\Users\\Sky1in3\\Desktop\\result.html");
            if (!file.exists()) {
                file.createNewFile();
            }
            // 设置输出流
            out = new FileWriter(file);
            // 模板输出静态文件
            template.process(map, out);
        } catch (TemplateNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedTemplateNameException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
